<?php

namespace app\adminapi\business;


use app\adminapi\extend\tools\excel\Excel;
use app\common\model\GoodsImages;
use app\common\model\SpecGoods;
use think\Exception;
use think\exception\DbException;
use think\facade\Db;

/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/1/6
 * Time: 3:08 下午
 * description: Goods.php
 * 处理商品有关逻辑的类
 */
class Goods {

    protected  $goodsModel;
    public function __construct(\app\common\model\Goods $goodsModel)
    {
        $this->goodsModel =  $goodsModel;

    }

    /**
     * 商品列表有关业务
     * @param int $limit
     * @param int $page
     * @param $goods_name
     * @param $goods_max_price
     * @param $goods_min_price
     * @return array|\think\response\Json|void
     * @throws \think\Exception
     */
    public  function goodsList($limit = 10,$page = 1,$goods_name,$goods_max_price,$goods_min_price){
        # 搜索条件
        $where = [];
        # 验证参数
        if (!empty($goods_name)) {
            $where[] = [
                'goods_name','like',"%$goods_name%"
            ];
        }
        if (!empty($goods_min_price) && !empty($goods_max_price)) {
            if (!is_numeric($goods_min_price) || !is_numeric($goods_max_price)) {
                return  fail(2001,'参数错误');
            }
            $where[] = [
                'goods_price','>',$goods_min_price
            ];
            $where[] = [
                'goods_price','<',$goods_max_price
            ];
        }
        $data = $this->goodsModel->where($where)->field('id,goods_name,cate_id,brand_id,goods_price')
            ->with(['category','brand','images'])
            ->order('goods_price')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->toArray();

        return  $data;
    }

    public function export(){
        # 操作模型 查询数据
        return Excel::export();
    }

    /**
     * 添加商品
     * @param $params
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function addGoods($params){

        # 增、删、改 多张表的时候、用事物
        Db::startTrans();
        try {
            # 第一步、添加商品基本信息 goods表
            $data  = [
                'goods_name' => $params['goods_name'],
                'goods_logo' => $params['goods_logo'],
                'type_id' => $params['type_id'],
                'brand_id' => $params['brand_id'],
                'cate_id' => $params['cate_id'],
                'goods_price' => $params['goods_price'],
                'goods_attr' => json_encode($params['attr'],JSON_UNESCAPED_UNICODE),
//                .....省略
            ];
            # 商品logo 缩略图 goods_logo 客户端传送过来的路径
            $image = \think\Image::open($params['goods_logo']);
            # 按照原图的比例生成一个最大为100*100的缩略图并保存为thumb.png
            $info = pathinfo($params['goods_logo']);
            # 重命名
            $new_name = md5(time().uniqid(11)).'.'.$info['extension'];
            $image->thumb(100, 100)->save($info['dirname'].'/'.$new_name);
            # 删除旧图片 unlink
            unlink($params['goods_logo']);
            # 数据库、保存新路径以及文件名
            $params['goods_logo'] =$info['dirname'].'/'.$new_name;
            $goods = \app\common\model\Goods::create($data); // # 商品添加后id
            $goods_id = $goods->id; # 获取自增ID
            # 第二步、添加商品图片信息 goods_images表
            $goodsImages = [];
            foreach ($params['goods_images'] as $goods_image) {
                # 商品相册、会生成、一张大图800*800 一张小图 400*400
                $image = \think\Image::open($goods_image);
                $info = pathinfo($goods_image);
                # 先生成大图
                # \uploads\goods\20210623\thumb_800_8fe36c024630569319ff2a2ffbcee847.jpg
                $big_name = 'thumb_800_'.md5(time()).'.'.$info['extension'];
                $image->thumb(800, 800)->save($info['dirname'].'/'.$big_name);
                # 生成小图
                $sma_name = 'thumb_400_'.md5(time()).'.'.$info['extension'];
                $image->thumb(400, 400)->save($info['dirname'].'/'.$sma_name);
                # 删除旧图片 unlink
                unlink($goods_image);
                $goodsImages[] = [
                    'goods_id' => $goods_id,
                    'pics_big' => $info['dirname'].'/'.$big_name,
                    'pics_sma' => $info['dirname'].'/'.$sma_name,
                ];
            }
            # 批量入库、构造数据
            $imagesModel = new GoodsImages();
            $imagesModel->saveAll($goodsImages);
            # 第三步、添加商品规格信息 spec_goods表
            # 构造数据
            $specGoods = [];
            foreach ($params['item'] as $value) {
                $specGoods[] = [
                    'goods_id' => $goods_id,
                    'value_ids' => $value['value_ids'],
                    'value_names' => $value['value_names'],
                    'price' => $value['price'],
                    'cost_price' => $value['cost_price'],
                    'store_count' => $value['store_count'],
                ];
            }
            # 批量入库
            $specGoodsModel = new SpecGoods();
            $specGoodsModel->saveAll($specGoods);
            // 提交事务
            Db::commit();
        }catch (DbException $exception) {
            // 回滚事务
            Db::rollback();
            throw new Exception("添加失败");
        }

    }

    /**
     * 获取商品详情
     * @param $id
     * @return array
     * @throws Exception
     */
    public  static function getInfo($id){
        # 商品基本信息
        $goodsInfo =  \app\common\model\Goods::with(['category','brand','images','type'])->field('id,goods_name,goods_price,goods_logo,brand_id,cate_id,type_id')->find($id)->toArray();
        # type_id已知
        $typeInfo = \app\common\model\Type::with(['spec','spec.specValue','attr'])->hidden(['create_time','delete_time','update_time'])->find($goodsInfo['type_id'])->toArray();
        $goodsInfo['type_info'] = $typeInfo;
        return  $goodsInfo;
    }

    /**
     * 删除商品
     * @param $id
     * @return bool
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteGoods($id){
        # 开启事物
        Db::startTrans();
        try {
            # 第一步 删除相册表
//            方式一、条件删除
            $result = GoodsImages::destroy(['goods_id'=> $id]);
            if (!$result) {
                throw new Exception("相册删除失败");
            }
//            方式二、先查询、再删除
            # 第二步 删除sku表
            $result = SpecGoods::destroy(['goods_id' => $id]);
            if (!$result) {
                throw new Exception("sku删除失败");
            }
            # 第三部 删除spu表
            $result = \app\common\model\Goods::destroy($id);
            if (!$result) {
                throw new Exception("spu删除失败");
            }
            # 提交事物
            DB::commit();
            return true;
        }catch (DbException $exception) {
            // 回滚事务
            Db::rollback();
            throw new Exception($exception->getMessage()?:"删除失败");
        }
    }

}